package com.heiyu.api.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.heiyu.api.request.*;
import com.heiyu.api.response.BigAuthFollowListResponse;
import com.heiyu.api.response.BigAuthorListResponse;
import com.heiyu.api.response.CollectArticleListResponse;
import com.heiyu.api.response.CommonResponse;
import com.heiyu.api.response.model.*;
import com.heiyu.constants.ResponseMsgEnum;
import com.heiyu.controller.ApiBaseController;
import com.heiyu.dao.*;
import com.heiyu.entity.*;
import com.heiyu.utils.DefaultImgUtils;
import com.heiyu.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(description = "大咖相关")
@RestController
@RequestMapping("/api/v1/author")
public class BigAuthorController extends ApiBaseController {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ArticleInfoMapper articleInfoMapper;
    @Autowired
    private BigAuthorFollowMapper bigAuthorFollowMapper;
    @Autowired
    private ArticleLikeMapper articleLikeMapper;
    @Autowired
    private UserArticleCollectMapper userArticleCollectMapper;
    @Autowired
    private ArticleAssessInfoMapper articleAssessInfoMapper;

    @ApiOperation(value = "大咖说列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public BigAuthorListResponse list(@ModelAttribute BigAuthorListRequest request) {
        BigAuthorListResponse response = new BigAuthorListResponse();
        UserInfo userInfo = getUser();
        response.setData(new BigAuthorListModel());
        Map<String, Object> param = PageUtils.newParam(request.getPageIndex(), request.getPageSize());
        param.put("itemId",10);
        List<ArticleInfo> list = null;
        if (request.getUserId() != null) {
            param.put("userId", request.getUserId());
            UserInfo author = this.userInfoMapper.selectPrimary(request.getUserId());
            response.getData().setAvator(author.getAvator());
            response.getData().setAuthorName(getNickName(author));
            Map<String, Object> followParam = Maps.newHashMap();
            followParam.put("authorId", request.getUserId());
            response.getData().setFollowNum(this.bigAuthorFollowMapper.count(followParam));
            if(userInfo != null){
                followParam.put("userId",userInfo.getId());
                response.getData().setIsFoucus(this.bigAuthorFollowMapper.count(followParam)>0?"1":"0");
            }else{
                response.getData().setIsFoucus("0");
            }
            followParam = Maps.newHashMap();
            followParam.put("itemId", 10);
            followParam.put("userId", request.getUserId());
            followParam.put("articleType", "2");
            response.getData().setArticleNum(this.articleInfoMapper.count(followParam));
            followParam.remove("articleType");
            followParam.put("articleType", "1");
            response.getData().setDynamicNum(this.articleInfoMapper.count(followParam));
        } else {
            param.put("userId", 0);
        }
        list = this.articleInfoMapper.itemList(param);
        if (!CollectionUtils.isEmpty(list)) {
            BigAuthArticleEntity entity;
            response.getData().setList(Lists.newArrayList());
            ArticleLike like;
            List<ArticleLike> likeList;
            UserInfo author;
            Map<String, Object> articleCollect = Maps.newHashMap();
            for (ArticleInfo info : list) {
                author = this.userInfoMapper.selectPrimary(info.getUserId());
                entity = new BigAuthArticleEntity();
                like = new ArticleLike();
                like.setArticleId(info.getId());
                if (userInfo != null) {
                    like.setUserId(userInfo.getId());
                    likeList = this.articleLikeMapper.selectList(like);
                    if (likeList != null && likeList.size() > 0) {
                        entity.setIsGood(likeList.get(0).getIsGood());
                    }
                    like.setUserId(null);
                }
                entity.setArticleId(info.getId());
                entity.setAuthor(info.getAuthorName());
                entity.setImgUrl(info.getImgUrl());
                if(info != null && info.getArticleType()==1){
                    entity.setMaxLine(6);
                }else{
                    entity.setMaxLine(3);
                }

                entity.setTitle(info.getTitle());
                entity.setContent(info.getContent());
                entity.setAuthorId(info.getUserId());
                entity.setArticleType(""+info.getArticleType());
                if(author != null){
                    entity.setAvator(author.getAvator());
                    entity.setAuthor(getNickName(author));
                }
                entity.setTimestamp(Integer.valueOf(info.getCreatedTime().getTime() / 1000 + ""));
                like.setIsGood("1");
                entity.setGoodNum(articleLikeMapper.loveCount(like));
                like.setIsGood("0");
                entity.setBadNum(articleLikeMapper.loveCount(like));
                entity.setShareNum(info.getShareTimes() == null ? 0 : info.getShareTimes());
                Map<String,Object> articleAssessParam = Maps.newHashMap();
                articleAssessParam.put("articleId",info.getId());
                entity.setAssessNum(this.articleAssessInfoMapper.count(articleAssessParam));
                if (info.getArticleType() == null || info.getArticleType()==2) {
                    articleCollect.put("articleId", info.getId());
                    entity.setCollectNum(this.userArticleCollectMapper.count(articleCollect));
                    if(userInfo != null){
                        articleCollect.put("userId",userInfo.getId());
                        entity.setIsCollect(this.userArticleCollectMapper.count(articleCollect)>0?"1":"0");
                    }
                }
                if(userInfo != null){
                    if(StringUtils.isEmpty(response.getData().getIsFoucus())){
                        param = PageUtils.newParam(0,20);
                        param.put("authorId",info.getUserId());
                        param.put("userId",userInfo.getId());
                        entity.setIsFocus(this.bigAuthorFollowMapper.count(param)>0?"1":"0");
                    }else{
                        entity.setIsFocus(response.getData().getIsFoucus());
                    }
                }else{
                    entity.setIsCollect("0");
                }
                response.getData().getList().add(entity);
            }
        }
        response.success();
        return response;
    }

    @ApiOperation(value = "我的关注")
    @RequestMapping(value = "follow/list", method = RequestMethod.GET)
    public BigAuthFollowListResponse followList(@ModelAttribute BigAuthFollowListRequest request) {
        BigAuthFollowListResponse response = new BigAuthFollowListResponse();
        response.setData(new BigAuthFollowModel());
        response.getData().setList(Lists.newArrayList());
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.setMsg(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        BigAuthorFollow follow = new BigAuthorFollow();
        follow.setUserId(userInfo.getId());
        List<BigAuthorFollow> list = this.bigAuthorFollowMapper.selectList(follow);
        if(!CollectionUtils.isEmpty(list)){
            UserInfo author;
            BigAuthFollowInfo entity;
            for(BigAuthorFollow info:list){
                entity = new BigAuthFollowInfo();
                author = this.userInfoMapper.selectPrimary(info.getAuthorId());
                entity.setAuthorId(author.getId());
                entity.setAuthorName(getNickName(author));
                entity.setAvator(author.getAvator());
                entity.setIsFocus("1");
                entity.setMessageStatus(info.getMessagePushConfig());
                entity.setLastUpdateTime(lastUpdateTime(info.getAuthorId()));
                response.getData().getList().add(entity);
            }
        }
        response.success();
        return response;
    }


    private Integer lastUpdateTime(Long userId){
            ArticleInfo info = this.articleInfoMapper.lastArticle(userId);
            if(info != null){
                return Integer.valueOf(info.getCreatedTime().getTime()/1000+"");
            }
            return 0;
    }

    @ApiOperation(value = "关注/取消关注大咖")
    @RequestMapping(value = "follow/author/update", method = RequestMethod.POST)
    public CommonResponse followAuth(@RequestBody FollowAuthReqquest reqquest) {
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.setMsg(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        if (reqquest.getFollowAuthId() == null || reqquest.getFollowAuthId() == 0) {
            response.setMsg("参数错误");
            return response;
        }
        BigAuthorFollow follow = new BigAuthorFollow();
        follow.setAuthorId(reqquest.getFollowAuthId());
        follow.setUserId(userInfo.getId());
        List<BigAuthorFollow> list = this.bigAuthorFollowMapper.selectList(follow);
        if (CollectionUtils.isEmpty(list)) {
            follow.setCreatedTime(new Date());
            follow.setModifyTime(new Date());
            follow.setIsDeleted("0");
            follow.setMessagePushConfig("1");
            this.bigAuthorFollowMapper.insert(follow);
        } else {
            this.bigAuthorFollowMapper.delete(list.get(0).getId());
        }
        response.success();
        return response;
    }

    @ApiOperation(value = "开启/取消大咖动态通知")
    @RequestMapping(value = "follow/message/update", method = RequestMethod.POST)
    public CommonResponse followAuthMessage(@RequestBody FollowAuthReqquest reqquest) {
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.setMsg(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        BigAuthorFollow follow = new BigAuthorFollow();
        follow.setAuthorId(reqquest.getFollowAuthId());
        follow.setUserId(userInfo.getId());
        List<BigAuthorFollow> list = this.bigAuthorFollowMapper.selectList(follow);
        if (CollectionUtils.isEmpty(list)) {
            response.error("您未关注该大咖");
            return response;
        } else {
            list.get(0).setMessagePushConfig(list.get(0).getMessagePushConfig().equals("1") ? "0" : "1");
            this.bigAuthorFollowMapper.updateById(list.get(0));
        }
        response.success();
        return response;
    }

    @ApiOperation(value = "收藏文章列表")
    @RequestMapping(value = "collect/list", method = RequestMethod.GET)
    public CollectArticleListResponse collectArticleList(@ModelAttribute CollectArticleListRequest request) {
        CollectArticleListResponse response = new CollectArticleListResponse();
        response.setData(new CollectArticleModel());
        response.getData().setList(Lists.newArrayList());
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.setMsg(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        UserArticleCollect collect = new UserArticleCollect();
        collect.setUserId(userInfo.getId());
        List<UserArticleCollect> list = this.userArticleCollectMapper.selectList(collect);
        if(!CollectionUtils.isEmpty(list)){
            ArticleEntity entity;
            ArticleInfo articleInfo;
            ArticleLike like  = new ArticleLike();
            UserInfo author;
            like.setIsGood("1");
            for(UserArticleCollect info:list){
                like.setArticleId(info.getArticleId());
                articleInfo = this.articleInfoMapper.selectPrimary(info.getArticleId());
                entity = new ArticleEntity();
                entity.setArticleId(articleInfo.getId());
                if(StringUtils.isEmpty(articleInfo.getImgUrl())){
                    entity.setImgUrl(DefaultImgUtils.getDefaultImg());
                }else
                entity.setImgUrl(articleInfo.getImgUrl());
                entity.setTitle(articleInfo.getTitle());
                entity.setTimestamp(Integer.valueOf(articleInfo.getCreatedTime().getTime()/1000+""));
                author = this.userInfoMapper.selectPrimary(articleInfo.getUserId());
                if(author == null){
                    entity.setAuthor(articleInfo.getAuthorName());
                }else{
                    entity.setAuthor(getNickName(author));
                }
                entity.setGoodNum(this.articleLikeMapper.loveCount(like));
                response.getData().getList().add(entity);
            }
        }
        response.success();
        return response;
    }

    @ApiOperation(value = "收藏/取消收藏文章接口")
    @RequestMapping(value = "collect/update", method = RequestMethod.POST)
    public CommonResponse collectArticle(@RequestBody CollectArticleRequest request) {
        CommonResponse response = new CommonResponse();
        UserInfo userInfo = getUser();
        if (userInfo == null) {
            response.setMsg(ResponseMsgEnum.USER_NOT_LOGIN);
            return response;
        }
        UserArticleCollect collect = new UserArticleCollect();
        collect.setArticleId(request.getArticleId());
        collect.setUserId(userInfo.getId());
        List<UserArticleCollect> list = this.userArticleCollectMapper.selectList(collect);
        if(CollectionUtils.isEmpty(list)){
            collect.setCreatedTime(new Date());
            collect.setModifyTime(new Date());
            collect.setIsDeleted("0");
            this.userArticleCollectMapper.insert(collect);
        }else{
            this.userArticleCollectMapper.delete(list.get(0).getId());
        }
        response.success();
        return response;
    }
}
